package org.ricks.net.action.rpc;

import org.ricks.ioc.utils.ReflectUtils;
import org.ricks.net.action.ActionHandler;
import org.ricks.net.action.Task;
import org.ricks.net.action.context.FlowContext;
import org.ricks.net.action.context.head.HeadMeta;
import java.lang.reflect.Method;

public class RpcHandler extends ActionHandler {
    private final RpcMetrics metrics;

    // 优化11: 添加指标监控
    public RpcHandler(Object bean, Method method, Task task,
                      Class<? extends FlowContext<? extends HeadMeta>> contextClazz,
                      RpcMetrics metrics) {
        super(bean, method, task, contextClazz);
        this.metrics = metrics;
    }

    @Override
    public void invoke(FlowContext<? extends HeadMeta> context) {
        if (!context.headMeta.isRpc() || context.headMeta.isRpcResponse()) {
            return;
        }

        long startTime = System.nanoTime();
        try {
            ReflectUtils.invokeMethod(bean, method, context);
            metrics.recordProcessSuccess(System.nanoTime() - startTime);
        } catch (Exception e) {
            metrics.recordProcessError();
            context.rpcError(-1, "RPC invocation error: " + e.getMessage());
        }
    }
}